package cn.cuilan.client;

import cn.cuilan.client.core.ClientHelper;
import cn.cuilan.common.entity.HttpEntity;
import cn.cuilan.common.entity.ProtocolMessage;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class Test {

    @Resource
    private ClientHelper clientHelper;

    @PostConstruct
    public void init() {
        HttpEntity httpEntity = new HttpEntity();

        String url = "https://cn.bing.com/";
        httpEntity.setUrl(url);
        httpEntity.setMethod("GET");

        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        requestHeaders.put("accept-encoding", "gzip, deflate, br");
        requestHeaders.put("accept-language", "zh-CN,zh;q=0.9");
        requestHeaders.put("cache-control", "max-age=0");
        requestHeaders.put("cookie", "MUID=3426312719946E531BAE3FB118EB6FAF; SRCHD=AF=NOFORM; SRCHUID=V=2&GUID=23ECEFF909FA439F9CFDC182648E0B4D&dmnchg=1; MUIDB=3426312719946E531BAE3FB118EB6FAF; ABDEF=V=0&ABDV=0&MRB=1585041166047&MRNB=0; SRCHUSR=DOB=20200324&T=1585382228000; _EDGE_S=SID=3BF8A25B81816FD43665ACC080AF6E2C; _SS=SID=3BF8A25B81816FD43665ACC080AF6E2C&bIm=804; ipv6=hit=1585407744006&t=4; SRCHHPGUSR=CW=1903&CH=410&DPR=1&UTC=480&HV=1585404144&WTS=63721000944");
        requestHeaders.put("sec-fetch-dest", "document");
        requestHeaders.put("sec-fetch-mode", "navigate");
        requestHeaders.put("sec-fetch-site", "none");
        requestHeaders.put("sec-fetch-user", "?1");
        requestHeaders.put("upgrade-insecure-requests", "1");
        requestHeaders.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36");
        httpEntity.setHeaders(requestHeaders);

        ProtocolMessage message = clientHelper.doSendWithNetty(httpEntity);
        HttpEntity responseEntity = (HttpEntity) message;
        Map<String, String> headers = responseEntity.getHeaders();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            log.info(entry.getKey() + ": " + entry.getValue());
        }

        ResponseBody responseBody = ResponseBody.create(responseEntity.getBody(), MediaType.get(responseEntity.getHeaders().get("Content-Type")));
        try {
            String string = responseBody.string();
            log.info(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
